<template>
  <div class="discord-management">
    <el-card class="discord-card">
      <template #header>
        <div class="card-header">
          <span>Discord账号管理</span>
          <el-button type="primary" @click="handleAdd">
            添加账号
          </el-button>
        </div>
      </template>

      <el-table
        :data="accountList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" min-width="180" />
        <el-table-column prop="email" label="邮箱" min-width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '正常' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLogin" label="最后登录" width="180" />
        <el-table-column label="操作" width="280">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                :type="row.status === 'active' ? 'danger' : 'success'"
                size="small"
                @click="handleToggleStatus(row)"
              >
                {{ row.status === 'active' ? '禁用' : '启用' }}
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="handleVerify(row)"
              >
                验证
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="batch-actions" v-if="selectedAccounts.length">
        <el-button-group>
          <el-button type="danger" @click="handleBatchDelete">
            批量删除
          </el-button>
          <el-button type="warning" @click="handleBatchVerify">
            批量验证
          </el-button>
        </el-button-group>
      </div>
    </el-card>

    <!-- 添加/编辑账号对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加Discord账号' : '编辑Discord账号'"
      width="500px"
    >
      <el-form
        ref="accountFormRef"
        :model="accountForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="accountForm.username" placeholder="请输入Discord用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="accountForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="accountForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="Token" prop="token">
          <el-input
            v-model="accountForm.token"
            type="password"
            placeholder="请输入Discord Token"
            show-password
          />
        </el-form-item>
        <el-form-item label="代理" prop="proxy">
          <el-input v-model="accountForm.proxy" placeholder="请输入代理地址（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const accountFormRef = ref(null)
const selectedAccounts = ref([])

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入Discord用户名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  token: [
    { required: true, message: '请输入Discord Token', trigger: 'blur' }
  ]
}

// 账号表单
const accountForm = reactive({
  username: '',
  email: '',
  password: '',
  token: '',
  proxy: ''
})

// 模拟数据
const accountList = ref([
  {
    id: 1,
    username: 'user1#1234',
    email: 'user1@example.com',
    status: 'active',
    lastLogin: '2025-02-22 10:30:00'
  },
  {
    id: 2,
    username: 'user2#5678',
    email: 'user2@example.com',
    status: 'inactive',
    lastLogin: '2025-02-21 15:45:00'
  }
])

// 处理多选变化
const handleSelectionChange = (selection) => {
  selectedAccounts.value = selection
}

// 添加账号
const handleAdd = () => {
  dialogType.value = 'add'
  accountForm.username = ''
  accountForm.email = ''
  accountForm.password = ''
  accountForm.token = ''
  accountForm.proxy = ''
  dialogVisible.value = true
}

// 编辑账号
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(accountForm, row)
  dialogVisible.value = true
}

// 验证账号
const handleVerify = async (row) => {
  try {
    loading.value = true
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success(`账号 ${row.username} 验证成功`)
  } catch (error) {
    ElMessage.error(`账号 ${row.username} 验证失败`)
  } finally {
    loading.value = false
  }
}

// 删除账号
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这个Discord账号吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    accountList.value = accountList.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
  })
}

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    loading.value = true
    await new Promise(resolve => setTimeout(resolve, 1000))
    const index = accountList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      accountList.value[index].status = row.status === 'active' ? 'inactive' : 'active'
      ElMessage.success(`${row.status === 'active' ? '禁用' : '启用'}成功`)
    }
  } finally {
    loading.value = false
  }
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedAccounts.value.length) return
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedAccounts.value.length} 个账号吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const selectedIds = selectedAccounts.value.map(row => row.id)
    accountList.value = accountList.value.filter(item => !selectedIds.includes(item.id))
    selectedAccounts.value = []
    ElMessage.success('批量删除成功')
  })
}

// 批量验证
const handleBatchVerify = async () => {
  if (!selectedAccounts.value.length) return

  try {
    loading.value = true
    await Promise.all(selectedAccounts.value.map(async (account) => {
      await new Promise(resolve => setTimeout(resolve, 1000))
      return account
    }))
    ElMessage.success(`已完成 ${selectedAccounts.value.length} 个账号的验证`)
  } catch (error) {
    ElMessage.error('部分账号验证失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!accountFormRef.value) return
  
  await accountFormRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 添加新账号
        const newAccount = {
          id: Date.now(),
          ...accountForm,
          status: 'active',
          lastLogin: '-'
        }
        accountList.value.push(newAccount)
        ElMessage.success('添加成功')
      } else {
        // 更新现有账号
        const index = accountList.value.findIndex(item => item.id === accountForm.id)
        if (index !== -1) {
          accountList.value[index] = { ...accountList.value[index], ...accountForm }
          ElMessage.success('更新成功')
        }
      }
      dialogVisible.value = false
    }
  })
}
</script>

<style scoped>
.discord-management {
  padding: 20px;
}

.discord-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button-group) {
  .el-button {
    padding: 5px 12px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
